package com.openbravo.data.loader.ui;

import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;

import com.openbravo.data.loader.LocalRes;
import com.openbravo.data.loader.query.QBFParameter;
import com.openbravo.data.loader.query.QBFParameters;
import com.openbravo.data.model.Field;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;

public abstract class JQBFParametersPanel extends JPanel {
	Field[] fields;
	private JPanel panel_1;
	private List<JQBFParameterPanel> paramterList;
	/**
	 * Create the panel.
	 */
	public JQBFParametersPanel() {
		initComponents();
	}
	
	private void initComponents() {
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel = new JPanel();
		add(panel, BorderLayout.SOUTH);
		panel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
		
		JButton btnNewButton = new JButton(LocalRes.getIntString("button.ok"));
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				okProdcess(e);
			}
		});
		
		JButton btnNewButton_2 = new JButton(LocalRes.getIntString("button.add"));
		btnNewButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				addParameterPanel();
				panel_1.revalidate();
			}
		});
		panel.add(btnNewButton_2);
		panel.add(btnNewButton);
		
		JButton btnNewButton_1 = new JButton(LocalRes.getIntString("button.resert"));
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				resertProcess(e);
			}
		});
		panel.add(btnNewButton_1);
		
	    panel_1 = new JPanel();
		add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));
	}

	protected void addParameterPanel() {
		JQBFParameterPanel parameterPanel=new JQBFParameterPanel();
		paramterList.add(parameterPanel);
		parameterPanel.setFields(fields);
		panel_1.add(parameterPanel);
	}
	
	
	
	protected void resertProcess(ActionEvent e) {
		for(JQBFParameterPanel p:paramterList){
		    p.resert();
		}
		
	}
	protected void okProdcess(ActionEvent e) {
		QBFParameters paras=new QBFParameters();
		QBFParameter para;
		for(JQBFParameterPanel p:paramterList){
		    para=p.getQBFParameter();
			if(para!=null)
				if(p.getLinkType()==QBFParameters.LINKTYPE_Or)
					paras.or(para);
				else
				   paras.and(para);
		}
		doQBFParametersFilter(paras);
	}
	
	public void setShowFieldCount(int num){
		paramterList=new ArrayList<JQBFParameterPanel>();
		for(int i=0;i<num;i++)
			addParameterPanel();
	}
	
	public void setFields(Field[] fields){
		this.fields=fields;
		for(JQBFParameterPanel p:paramterList){
			p.setFields(fields);
		}
	}
	
	public abstract void doQBFParametersFilter(QBFParameters paras);
	
	
}
